package com.example.application2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class FilewrActivity extends AppCompatActivity {

    private final static String MyFileName = "myfile";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filewr);

        Button fw = findViewById(R.id.btn_fw);
        Button fr = findViewById(R.id.btn_fr);

        fw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OutputStream out = null;
                try {
                    FileOutputStream fileOutputStream = openFileOutput(MyFileName, MODE_PRIVATE);
                    out = new BufferedOutputStream(fileOutputStream);
                    String content = "2016011427 陈希星";
                    try {
                        out.write(content.getBytes(StandardCharsets.UTF_8));
                    } finally {
                        if (out != null){
                            out.close();
                        }
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        fr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputStream in = null;
                try {
                    FileInputStream fileInputStream = openFileInput(MyFileName);
                    in = new BufferedInputStream(fileInputStream);
                    int c;
                    StringBuilder stringBuilder = new StringBuilder("");
                    try {
                        while ((c = in.read()) != -1){
                            stringBuilder.append((char) c);
                        }
                        Toast.makeText(FilewrActivity.this, stringBuilder.toString(), Toast.LENGTH_LONG).show();
                    } finally {
                        if (in != null){
                            in.close();
                        }
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}